/*  
 *  ------ [ZB_09a] - complete example send  ------
 *  
 *  Explanation: This is a complete example for XBee-ZigBee
 *  This example shows how to send a packet using unicast 64-bit
 *  destination address. After sending the packet, Waspmote waits
 *  for the response of the receiver and prints all available 
 *  information  
 *  
 *  Copyright (C) 2012 Libelium Comunicaciones Distribuidas S.L. 
 *  http://www.libelium.com 
 *  
 *  This program is free software: you can redistribute it and/or modify 
 *  it under the terms of the GNU General Public License as published by 
 *  the Free Software Foundation, either version 3 of the License, or 
 *  (at your option) any later version. 
 *  
 *  This program is distributed in the hope that it will be useful, 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 *  GNU General Public License for more details. 
 *  
 *  You should have received a copy of the GNU General Public License 
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 *  
 *  Version:           0.1 
 *  Design:            David Gascón 
 *  Implementation:    Yuri Carmona
 */




#include <MakeSureXBeeZB.h>
#include <MakeSureFrame.h>

///////  Input parameters  //////////
char* DESTINATION="0013A20040A91B0F";
////////////////////////////////////

char* MoteID="MakeSure_Xbee";

char* MAC_LOW="40A91B0F";

String s;
// pointer to the packet to send
packetXBee* packet;

// variable to store time stamp
long previous=0;


void setup()
{
  // init Serial port
	Serial.begin(9600);
  Serial.println("ZB_09a complete example");
 
  //////////////////////////
  // 1. init XBee
  //////////////////////////
  xbeeZB.ON();

  delay(3000);
  
  //////////////////////////
  // 2. check XBee's network parameters
  //////////////////////////
  checkNetworkParams();
  
}


void loop()
{
  //////////////////////////
  // 3. create frame
  //////////////////////////  
  
  // 3.1. create new frame
  frame.createFrame(ASCII,MAC_LOW,MoteID);  
  
  // 3.2. add frame fields
  frame.addSensor(SENSOR_STR, "Complete example message"); 
  //frame.addSensor(SENSOR_RAM, freeMemory(); 
  
 
  //////////////////////////
  // 4. send packet
  //////////////////////////   

  // 4.1. set packet to send:
  packet=(packetXBee*) calloc(1,sizeof(packetXBee)); // memory allocation
  packet->mode=UNICAST; // set Broadcast mode

  // 4.2. set Destination parameters
  xbeeZB.setDestinationParams(packet, DESTINATION, frame.buffer, frame.length);

  // 4.3. send data
  xbeeZB.sendXBee(packet);

  // 4.4. check TX flag
  if( xbeeZB.error_TX == 0 ) 
  {   
    Serial.print("ok"); 
  }
  else 
  {
    Serial.print("error"); 
  }
  
  // 4.5. free memory
  free(packet);
  packet=NULL; 


  //////////////////////////
  // 5. Receive answer
  ////////////////////////// 

  // 5.1. wait the answer for 5 seconds
  previous=millis();
  while( (millis()-previous) < 5000 )
  {
    // check available data in RX buffer
    if( xbeeZB.available() > 0 ) 
    {
      // parse information
      xbeeZB.treatData(); 

      // check RX flag after 'treatData'
      if( !xbeeZB.error_RX ) 
      {
        // check available packets
        while( xbeeZB.pos>0 )
        {
          /*** Available info in 'xbeeZB.packet_finished' structure ***/
          Serial.print("\n---------- New Packet Received ---------------");          


          // 1.Print Source's MAC address
          Serial.print("MAC Address Source: ");          
          Serial.print(xbeeZB.packet_finished[xbeeZB.pos-1]->macSH[0],HEX); 
          Serial.print(xbeeZB.packet_finished[xbeeZB.pos-1]->macSH[1],HEX); 
          Serial.print(xbeeZB.packet_finished[xbeeZB.pos-1]->macSH[2],HEX); 
          Serial.print(xbeeZB.packet_finished[xbeeZB.pos-1]->macSH[3],HEX); 
          Serial.print(xbeeZB.packet_finished[xbeeZB.pos-1]->macSL[0],HEX); 
          Serial.print(xbeeZB.packet_finished[xbeeZB.pos-1]->macSL[1],HEX); 
          Serial.print(xbeeZB.packet_finished[xbeeZB.pos-1]->macSL[2],HEX); 
          Serial.print(xbeeZB.packet_finished[xbeeZB.pos-1]->macSL[3],HEX);  
          Serial.println("");


          // 2.Print Origin's sending mode: 0=unicast; 1=broadcast;     
          Serial.print("UNICAST(0) or BROADCAST(1): ");   
          Serial.println(xbeeZB.packet_finished[xbeeZB.pos-1]->mode,HEX);

         
          // 3.Print data field
          Serial.print("Data: ");                    
          for(int i=0;i<xbeeZB.packet_finished[xbeeZB.pos-1]->data_length;i++)          
          {
			  s=String(xbeeZB.packet_finished[xbeeZB.pos-1]->data[i]);
            Serial.print(s);          
          }
          Serial.println("");


          // free variable 
          free(xbeeZB.packet_finished[xbeeZB.pos-1]);
          xbeeZB.packet_finished[xbeeZB.pos-1]=NULL;

          // decrement packet counter
          xbeeZB.pos--;       

          Serial.println("----------------------------------------------");
        }
        previous=millis();
      }
    }
  }/* end while */

  
}





/*******************************************
 *
 *  checkNetworkParams - Check operating
 *  network parameters in the XBee module
 *
 *******************************************/
void checkNetworkParams()
{
  // 1. get operating 64-b PAN ID
  xbeeZB.getOperating64PAN();

  // 2. wait for association indication
  xbeeZB.getAssociationIndication();
 
  while( xbeeZB.associationIndication != 0 )
  {   
    printAssociationState();
   
    delay(2000);
    
    // get operating 64-b PAN ID
    xbeeZB.getOperating64PAN();

    Serial.print("operating 64-b PAN ID: ");
    Serial.print(xbeeZB.operating64PAN[0],HEX);
    Serial.print(xbeeZB.operating64PAN[1],HEX);
    Serial.print(xbeeZB.operating64PAN[2],HEX);
    Serial.print(xbeeZB.operating64PAN[3],HEX);
    Serial.print(xbeeZB.operating64PAN[4],HEX);
    Serial.print(xbeeZB.operating64PAN[5],HEX);
    Serial.print(xbeeZB.operating64PAN[6],HEX);
    Serial.print(xbeeZB.operating64PAN[7],HEX);
    Serial.println();     
    
    xbeeZB.getAssociationIndication();
  }

  Serial.print("\nJoined a network!");

  // 3. get network parameters 
  xbeeZB.getOperating16PAN();
  xbeeZB.getOperating64PAN();
  xbeeZB.getChannel();

  Serial.print("operating 16-b PAN ID: ");
  Serial.print(xbeeZB.operating16PAN[0],HEX);
  Serial.print(xbeeZB.operating16PAN[1],HEX);
  Serial.println();

  Serial.print("operating 64-b PAN ID: ");
  Serial.print(xbeeZB.operating64PAN[0],HEX);
  Serial.print(xbeeZB.operating64PAN[1],HEX);
  Serial.print(xbeeZB.operating64PAN[2],HEX);
  Serial.print(xbeeZB.operating64PAN[3],HEX);
  Serial.print(xbeeZB.operating64PAN[4],HEX);
  Serial.print(xbeeZB.operating64PAN[5],HEX);
  Serial.print(xbeeZB.operating64PAN[6],HEX);
  Serial.print(xbeeZB.operating64PAN[7],HEX);
  Serial.println();

  Serial.print("channel: ");
  Serial.print(xbeeZB.channel,HEX);
  Serial.println();

}





/*******************************************
 *
 *  printAssociationState - Print the state 
 *  of the association flag
 *
 *******************************************/
void printAssociationState()
{
  switch(xbeeZB.associationIndication)
  {
    case 0x00  :  Serial.print("Successfully formed or joined a network");
                  break;
    case 0x21  :  Serial.print("Scan found no PANs");
                  break;    
    case 0x22  :  Serial.print("Scan found no valid PANs based on current SC and ID settings");
                  break;    
    case 0x23  :  Serial.print("Valid Coordinator or Routers found, but they are not allowing joining (NJ expired)");
                  break;    
    case 0x24  :  Serial.print("No joinable beacons were found");
                  break;    
    case 0x25  :  Serial.print("Unexpected state, node should not be attempting to join at this time");
                  break;
    case 0x27  :  Serial.print("Node Joining attempt failed");
                  break;
    case 0x2A  :  Serial.print("Coordinator Start attempt failed");
                  break;
    case 0x2B  :  Serial.print("Checking for an existing coordinator");
                  break;
    case 0x2C  :  Serial.print("Attempt to leave the network failed");
                  break;
    case 0xAB  :  Serial.print("Attempted to join a device that did not respond.");
                  break;
    case 0xAC  :  Serial.print("Secure join error: network security key received unsecured");
                  break;
    case 0xAD  :  Serial.print("Secure join error: network security key not received");
                  break;
    case 0xAF  :  Serial.print("Secure join error: joining device does not have the right preconfigured link key");
                  break;
    case 0xFF  :  Serial.print("Scanning for a ZigBee network (routers and end devices)");
                  break;
    default    :  Serial.print("Unkown associationIndication");
                  break;  
  }
}

